import tornado
from tornado import gen,web,ioloop
from vo import BlogListViewObject
from vo import  SearchViewObject,BlogViewObject
from .indexBaseHttp import baseHttp
from logic import articleDao,navlistDao
from log import log
loop = ioloop.asyncio.get_event_loop()
#首页
class index(baseHttp):
    @gen.coroutine
    def get(self):
        p=self.get_argument("p",1)
        try:
            vo = BlogListViewObject.buildIndex(p)
            self.render("index/index.html", vo=vo)
        except IOError:
            log.error(IOError)
            self.redirect("/404")
#文章
class article(baseHttp):
    @gen.coroutine
    def get(self,aid):
        try:
            vo = BlogViewObject.build(aid)
            if vo.view:
                self.render("index/article/article.html", vo=vo)
            else:
                self.redirect("/404")
        except IOError:
            log.error(IOError)
            self.redirect("/404")

#拼音url取文章
class PinyinArticle(baseHttp):
    @tornado.gen.coroutine
    def get(self,urls):
        try:
            vo = BlogViewObject.buildurl(urls)
            if vo.view:
                self.render("index/article/article.html", vo=vo)
            else:
                self.redirect("/404")
        except IOError:
            log.error(IOError)
            self.redirect("/404")

#列表
class nav(baseHttp):
    @gen.coroutine
    def get(self,nid):
        p = int(self.get_argument("p", 1))
        try:
            nav = navlistDao.navlistDao().get(nid)
            if len(nav) > 0:
                if nav.get().type == 1:
                    vo = BlogListViewObject.buildBlog(nid,p)
                    self.render("index/article/list.html",vo=vo)
                    return
                if nav.get().type == 2:
                    vo = BlogListViewObject.BlogNavViewObject(nav.get())
                    self.render("index/article/article_nav.html",vo=vo)
                    return
                if nav.get().type == 3:
                    self.redirect(nav.get().url)
            else:
                self.redirect("/404")

        except IOError:
            log.error(IOError)
            self.redirect = self.redirect("/404")
#搜索
class search(baseHttp):
    @gen.coroutine
    def get(self):
        q=self.get_argument("q","linux")
        try:
            vo =SearchViewObject.build(q)
            self.render("index/article/search.html",vo=vo)
        except IOError:
            log.error(IOError)
            self.redirect("/404")